/*!
 * This file implements a list of movies.
 * THIS FILE IS NOT USED FOR THE MOMENT
 * @author Mazzer Yannis, Calingarayar Martial
 * @file movies.h
 */
#include <QSqlDatabase>
#include <QSqlTableModel>
#include <QModelIndex>
#include <QDataWidgetMapper>
#include "../liteconnector/liteconnector.h"
#include "movies.h"
#include "movie/movie.h"

Movies::Movies(QSqlDatabase &db, QWidget *parent) : QSqlTableModel(parent, db)
{
    this->setEditStrategy(QSqlTableModel::OnRowChange);
//    this->setSort(this->fieldIndex("numero"), Qt::AscendingOrder);
    connect(this, SIGNAL(layoutChanged()), this, SLOT(updateMovieList()));
//    connect(this, SIGNAL(modelReset()), this, SLOT(resetIndexes()));
}

Movies::~Movies()
{
    int size = this->movs.size();
    for(int i=0; i<size; i++) {
	delete movs.value(i);
    }
}

Movie *Movies::getMovie(const int &movieNumber)
{
    return this->movs[movieNumber];
}

Movie *Movies::getMovie(const QModelIndex &movieIndex)
{
    return this->movs[movieIndex.row()];
}

MovieList Movies::getMovieList()
{
    return this->movs;
}

int Movies::addMovie(Movie *newMovie, bool ok)
{
    if(movs.contains(newMovie)) {
	ok = false;
	return movs.indexOf(newMovie);
    }
    else {
	this->movs.append(newMovie);
	return 0;
    }

}

void Movies::removeMovie(Movie *oldMovie)
{
//    int index = movs.indexOf(oldMovie);
//    this->movs.removeAt(index);
}

void Movies::updateMovieList()
{
//    int size = this->rowCount();
//    if (size != -1) {
//	for (int i=0; i<size; i++){
//	    QSqlRecord tmp = this->record(i);
//	    Movie *newMovie = new Movie(i, tmp);
//	    Movie *newMovie = new Movie(i, this, (QWidget *)NULL);
//	    this->movs.append(newMovie);
//	    connect(newMovie, SIGNAL(commitToDb(int, QSqlRecord)),
//		    this, SLOT(updateDbRow(int, QSqlRecord)));
//	}
//    }

}

void Movies::resetIndexes()
{
//    int sqlsize = this->rowCount();
//    int listsize = this->movs.size();
//    if(sqlsize != -1 && listsize > 0) {
//	for(int i=0; i<listsize; i++) {
//	    for(int j=0; j<sqlsize; j++) {
//		if(this->record(j).value("numero") == this->movs[i]->getNumero())
//		{
//		    this->movs[i]->setIndex(j);
//		    break;
//		}
//	    }
//	}
//    }
}

void Movies::updateDbRow(int idx, QSqlRecord record)
{
    int ok;
    this->database().transaction();
    if(this->setRecord(idx, record)) {
//	ok = this->database().commit();
//	this->database().transaction();
//	ok = this->submitAll();
	qDebug() << "commited" << endl;
    }
//  else {
//	this->database().rollback();
//	qDebug() << "not commited" << endl;
//    }

    ok = this->database().commit();
    if(ok)
	qDebug() << "true" << endl;
    else
	qDebug() << "false" << endl;

}

QModelIndex Movies::persistentIndexModel(const int &idx)
{
    QModelIndexList tmp = this->persistentIndexList();
    return tmp[idx];
//    return this->persistentIndexList()[idx];
}
